package hcd.mynote;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.widget.*;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * A placeholder fragment containing a simple view.
 */
public class HomeActivityFragment extends Fragment {

    public HomeActivityFragment() {
    }

    private List<Note> notes;
    private ListviewAdapter listviewAdapter;
    private FloatingActionButton fab;
    private Button showUserButton;

    private boolean syncing = false;

    private String loginUsername = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getActivity().setTitle("我的笔记");
        setHasOptionsMenu(true);
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        fab = (FloatingActionButton) view.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditFragment fragment = new EditFragment();
                Bundle bundle = new Bundle();
                bundle.putString("user", loginUsername);
                fragment.setArguments(bundle);
                fragment.setEditBackListener(new OnEditBackListener() {
                    @Override
                    public void back() {
                        backFromEdit();
                    }
                });
                fab.setVisibility(View.GONE);
                ((HomeActivity) getActivity()).setCurrentFragment(HomeActivity.EDIT_FRAGMENT);
                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment, fragment)
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .addToBackStack(null)
                        .commit();

            }
        });


        notes = DataSupport.order("time desc").find(Note.class);

        ListView listView = (ListView) view.findViewById(R.id.list_view);
        listviewAdapter = new ListviewAdapter(this, notes);
        listView.setAdapter(listviewAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EditFragment fragment = new EditFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("note", notes.get(position));
                bundle.putString("user", loginUsername);
                fragment.setArguments(bundle);
                fragment.setEditBackListener(new OnEditBackListener() {
                    @Override
                    public void back() {
                        backFromEdit();
                    }
                });
                fab.setVisibility(View.GONE);
                ((HomeActivity) getActivity()).setCurrentFragment(HomeActivity.EDIT_FRAGMENT);
                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment, fragment)
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .addToBackStack(null)
                        .commit();
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                PopupMenu menu = new PopupMenu(getContext(), view);
                getActivity().getMenuInflater().inflate(R.menu.menu_item, menu.getMenu());
                menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.list_item_delete:
                                deleteNote(position);
                                return true;
//                            case R.id.list_item_multi:
//                                Toast.makeText(getContext(), "多选", Toast.LENGTH_SHORT).show();
//                                return true;
                            default:
                                return false;
                        }
                    }
                });
                menu.show();
                return true;
            }
        });

        final EditText searchText = (EditText) view.findViewById(R.id.search_text);
        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchNote(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        Button clearBtn = (Button) view.findViewById(R.id.search_text_clear);
        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchText.setText("");
            }
        });

        showUserButton = (Button) view.findViewById(R.id.show_user_btn);

        showUserButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goUserPanel();
            }
        });


        syncNotes();

        return view;
    }

    private void syncNotes(){
        SharedPreferences sp = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        loginUsername = sp.getString("username", null);
        if (loginUsername == null) {
            showUserButton.setText(R.string.home_login_hint);
            return;
        }
        showUserButton.setText("正在同步: " + loginUsername);
//        Toast.makeText(getContext(), "正在同步...", Toast.LENGTH_LONG).show();
        syncing = true;
        new Thread(){
            @Override
            public void run() {
                try {
                    ArrayList<Note> temp = new ArrayList<>();
                    temp.addAll(notes);
                    ArrayList<Note> bmobList = Bmob.getNotes(loginUsername);

                    for (Note cloud: bmobList){
                        boolean match = false;

                        for (Note local: notes){
                            if (cloud.getCreateTime() == local.getCreateTime()){
                                if (cloud.getTime() > local.getTime()){
                                    // 云端更加新
                                    cloud.save();
                                }else if (cloud.getTime() < local.getTime()) {
                                    // 本地更加新
                                    try{
                                        Bmob.saveNote(local, loginUsername);
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }

                                }
                                match = true;
                                temp.remove(local);
                                break;
                            }
                        }
                        if (!match){
                            // 本地没有云端的这个笔记
                            cloud.save();
                        }
                    }

                    // 剩下的笔记是不在云端上的
                    for (Note note: temp){
                        Bmob.saveNote(note, loginUsername);
//                        DataSupport.deleteAll(Note.class, "createTime = ?", String.valueOf(note.getCreateTime()));
                    }

                    syncHandler.obtainMessage(0).sendToTarget();
                } catch (Exception e) {
                    e.printStackTrace();
                    syncHandler.obtainMessage(1).sendToTarget();
                }

            }
        }.start();
    }


    private Handler syncHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            syncing = false;
            if (msg.what == 0){
                notes.clear();
                notes.addAll(DataSupport.order("time desc").find(Note.class));
                listviewAdapter.notifyDataSetChanged();
                showUserButton.setText("同步完成: " + loginUsername);
//                Toast.makeText(getContext(), "同步完成", Toast.LENGTH_SHORT).show();
            }else {
                showUserButton.setText("同步失败: " + loginUsername);
//                Toast.makeText(getContext(), "同步失败", Toast.LENGTH_SHORT).show();
            }


        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_sync){
            if (loginUsername == null || loginUsername.isEmpty()){
                // 跳转到登陆
                goUserPanel();
                return false;
            }
            if (!syncing)
                syncNotes();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void goUserPanel(){
        UserFragment fragment = new UserFragment();
        fragment.setUserChangeListener(new OnUserChangeListener() {
            @Override
            public void change() {
                syncNotes();
            }

            @Override
            public void back() {
                fab.setVisibility(View.VISIBLE);
            }
        });
        ((HomeActivity) getActivity()).setCurrentFragment(HomeActivity.USER_FRAGMENT);
        fab.setVisibility(View.GONE);
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment, fragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .addToBackStack(null)
                .commit();
    }

    private void backFromEdit(){
        fab.setVisibility(View.VISIBLE);
        notes.clear();
        notes.addAll(DataSupport.order("time desc").find(Note.class));
//        Log.d("backFromEdit", "notes: " + notes.size());
        listviewAdapter.notifyDataSetChanged();
        syncNotes();
    }

    private void deleteNote(final int row){
        new Thread(){
            @Override
            public void run() {
                try{
                    Bmob.deleteNote(String.valueOf(notes.get(row).getCreateTime()), loginUsername);
                    deleteNoteHandler.obtainMessage(0, row).sendToTarget();
                }catch (Exception e){
                    deleteNoteHandler.obtainMessage(1, row).sendToTarget();
                }

            }
        }.start();
    }
    private Handler deleteNoteHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0){
                int row = (int) msg.obj;
                DataSupport.deleteAll(Note.class, "createTime = ?", String.valueOf(notes.get(row).getCreateTime()));
                Toast.makeText(getContext(), "已删除", Toast.LENGTH_SHORT).show();
                notes.clear();
                notes.addAll(DataSupport.order("time desc").find(Note.class));
                listviewAdapter.notifyDataSetChanged();
            }else {
                Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();

            }
        }
    };

    public void searchNote(String keyword){
        if (keyword.isEmpty()){
            notes.clear();
            notes.addAll(DataSupport.order("time desc").find(Note.class));
            listviewAdapter.notifyDataSetChanged();
        }else {
            notes.clear();
            notes.addAll(DataSupport.where("title like '%"+keyword+"%' or content like '%"+keyword+"%'").order("time desc").find(Note.class));
            listviewAdapter.notifyDataSetChanged();
        }

    }



}
